var  schoolDom;
var  startDom;
var  endDom;
var  btnView;
var  appList;
var existSchoolId;
var existSchoolName;
var allowPrint = false;
$(function () {
    schoolDom = $('#school_id');
    startDom  = $('#startTime');
    endDom    = $('#endTime');
    btnView   = $('#bt_view_usage');
    appList   = $('#appList');
    existSchoolId   = $('#existSchoolId');
    existSchoolName   = $('#existSchoolName');
    // var appListHeight=window.innerHeight-44;
    // appList.css('height',appListHeight+'px');
    // schoolDom.select2();
    btnView.click(function () {
        setTimeout(function () {
            var schoolId    = schoolDom.val(),
                startTime   = startDom.val(),
                endTime     = endDom.val();
            if (!schoolId) {
                window.top.xhTop.showError('学校为必选项！');
                xhExtra.setBtnNormal(btnView);
                return false;
            }
            if (!startTime || !endTime) {
                window.top.xhTop.showError('时间不能为空！');
                xhExtra.setBtnNormal(btnView);
                return false;
            }
            startCache(schoolId, startTime, endTime);
            // $.ajax({
            //     url:baseUrl+'school_week/getAppData',
            //     data:{schoolId: schoolId, startTime: startTime, endTime: endTime},
            //     type:'POST',
            //     dataType:'json',
            //     success:function (data) {
            //         initApp(data);
            //     },
            //     error:function (data) {
            //         window.top.swal(
            //             data['responseText'],
            //             '',
            //             'error'
            //         );
            //     }
            // });
            // window.top.swal({
            //     title: '统计执行中！请耐心等待...',
            //     showConfirmButton: false,
            //     type: 'success',
            //     allowOutsideClick: false
            // });
            // setTimeout(function () {
            //     window.top.swal.close();
            // }, 30 * 1000);
        }, 0);
    });
    if ($('#school_area').length >= 1) {
       if (existSchoolId.val() !== undefined){//默认有学校id，进页面即自动查询加载数据
           schoolDom.select2({data:[{id:existSchoolId.val(),text:existSchoolName.val()}]}).val([existSchoolId.val()]).trigger('change');
           setTimeout(function () {
               var schoolId    = schoolDom.val(),
                   startTime   = startDom.val(),
                   endTime     = endDom.val();
               if (!schoolId) {
                   window.top.xhTop.showError('学校为必选项！');
                   xhExtra.setBtnNormal(btnView);
                   return false;
               }
               if (!startTime || !endTime) {
                   window.top.xhTop.showError('时间不能为空！');
                   xhExtra.setBtnNormal(btnView);
                   return false;
               }
               startCache(schoolId, startTime, endTime);
           }, 0);
       } else {//没有给默认学校
           schoolDom.select2();
           xhExtra.ajaxRequest('Other/getDep', {tag: 'XHYYB', depth: 2}, {check: true}, function (data) {
               data.unshift({id: 0, tag: '全部', text: '-全部-'});
               $('#school_area').select2({data: data}).change(function () {
                   xhExtra.ajaxRequest('Other/getSchoolByDep', {depId: $(this).val()}, {check: false}, function (schools) {
                       if (xhExtra.checkError(schools)) {
                           schoolDom.empty();
                           return false;
                       }
                       schoolDom.empty().select2({data: schools});
                   });
               });//.trigger('change');
           });
       }
    }
    else {
        schoolDom.select2();
    }
});
var timer;
function startCache (schoolId, startTime, endTime) {
    setTimeout(function () {
        swal({
            title: '后台统计中！请耐心等待...',
            text: '预计时间3分钟...',
            showConfirmButton: false,
            type: 'success',
            allowOutsideClick: false
        });
    }, 0);
    xhExtra.ajaxRequest('school_week/startAppCountCache', {schoolId: schoolId, startTime: startTime, endTime: endTime}, {check: false, timeout: 2}, function (data) {
        if (typeof data === 'object' && data.error) {
            xhExtra.setBtnNormal(btnView);
            window.top.xhTop.showError(data.error);
            swal.close();
            return false;
        }
        timer = setInterval(function () {
            checkCache(schoolId, startTime, endTime);
        }, 1000 * 5);
    });
}
function checkCache (schoolId, startTime, endTime) {
    xhExtra.ajaxRequest('school_week/checkAppCountCache', {schoolId: schoolId, startTime: startTime, endTime: endTime}, {check: false}, function (data) {
        if (data.code === 200) {
            clearInterval(timer);
            swal.close();
            xhExtra.ajaxRequest('school_week/getAppData', {schoolId: schoolId, startTime: startTime, endTime: endTime}, {check: false}, function (data) {
                if (xhExtra.checkError(data)) {
                    xhExtra.setBtnNormal(btnView);
                    return false;
                }
                initApp(data);
            });
        }
    });
}


function initApp(data) {
    xhExtra.setBtnNormal(btnView);
    allowPrint = true;
    if(data == []){
        return false;
    }
    initCommon(data['common']);
    initBrash(data['brush']['chinese'],'brush_chinese');
    initBrash(data['brush']['chineseColl'],'brush_chineseColl');
    initBrash(data['brush']['english'],'brush_english');
    initBrash(data['brush']['math'],'brush_math');
    initBrash(data['brush']['science'],'brush_science');
    initTrans(data['chineseBasic'],'chinese_basic');
    initTrans(data['speakTrain'],'speak_train');
    //关闭App
    window.top.swal.close();
    swal.close();
    appList.show();
}

function initCommon(data) {
    var str = '';
    if(data!=null && data.length>0 ) {
        str+='<tr class="info"> <th colspan="3">考核项目</th> <th colspan="8">云作业</th> <th>有效课堂</th> </tr>';
        str+='<tr class="info"> <th rowspan="3">老师/班级</th> <th rowspan="3">班级数量</th> <th rowspan="3">学生数量</th> <th rowspan="2" colspan="4">基础项</th> <th colspan="4">附加项</th> <th rowspan="3">完成次数</th> </tr>';
        str+='<tr class="info"> <th>分层</th> <th >错题卷组</th> <th >微课</th> <th >二次批改</th> </tr>';
        str+='<tr class="info"> <th>完成次数</th> <th>平均题量</th> <th>上交率</th> <th>批改率</th> <th>完成次数</th> <th>完成次数</th> <th>录制次数</th> <th>批改次数</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td style="word-wrap:break-word;">' + row['tchName'] + '<br>' + row['classNames'].join(',') + '</td>';
            str += '<td>' + row['classNum'] + '</td>';
            str += '<td>' + row['stuNum'] + '</td>';
            str += '<td>' + row['cloudTask']['taskFixNum'] + '</td>';
            str += '<td>' + row['cloudTask']['avgTopicNum'] + '</td>';
            str += '<td>' + (row['cloudTask']['uploadRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + (row['cloudTask']['correctRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + row['cloudTask']['taskGroupNum'] + '</td>';
            // str += '<td>' + (row['cloudTask']['completeGroupRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + row['cloudTask']['taskWrongNum'] + '</td>';
            str += '<td>' + row['cloudTask']['coursewareNum'] + '</td>';
            str += '<td>' + row['cloudTask']['taskRecorrectNum'] + '</td>';
            str += '<td>' + row['ztClass']['taskValidNum'] + '</td>';
            str += '</tr>'
        })
    };
    $('#common').find('table').empty().append(str);
}

function initBrash(data,seletor) {
    var str = '';
    if(data!=null && data.length>0 ) {
        str+='<tr class="info"> <th >班级</th> <th >老师</th> <th>人均题量</th> <th>布置次数</th> <th>上交率</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td>' + row['className'] + '</td>';
            str += '<td>' + row['tchName'] + '</td>';
            str += '<td>' + row['practiceNum'] + '</td>';
            str += '<td>' + row['taskFixNum'] + '</td>';
            str += '<td>' + (row['uploadRate'] * 100).toFixed(2) + '%</td>';
            str += '</tr>'
        })
    };
    $('#'+seletor).find('table').empty().append(str);
}

function initTrans(data,seletor) {
    var str = '';
    if(data!=null && data.length>0 ) {
        str+='<tr class="info"> <th>班级</th> <th>老师</th> <th>完成次数</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td>' + row['className'] + '</td>';
            str += '<td>' + row['tchName'] + '</td>';
            str += '<td>' + row['taskFixNum'] + '</td>';
            str += '</tr>'
        })
    };
    $('#'+seletor).find('table').empty().append(str);
}